package com.eureka.bclass.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 * @Author: lixing lixing_java@163.com
 * @Date: 2019/10/10 21:29
 */
public class RequestUtil {
    /**
     * @Description TODO 获取当前请求的完整URL
     * @Author lixing
     * @Date 2019/2/23 14:27
     * @Param [request]
     * @return http://192.168.223.128:8080/sxtelecom/balance/toBinding?name=lx&age=25&sex=1
     *
     * String scheme = request.getScheme(); // http
     * String serverName = request.getServerName(); // localhost
     * String serverPort = String.valueOf(request.getServerPort()); // 8080
     *
     * String contextPath = request.getContextPath(); // /warboot
     * String servletPath = request.getServletPath(); // /balance/toBinding
     * String requestURI = request.getRequestURI();  // /warboot/balance/toBinding
     */
    public static String getRequestUrl(HttpServletRequest request) {
        StringBuffer requestUrl = request.getRequestURL(); // 当前请求的链接对象（http://192.168.223.128:8080/xstelecom/test）
        Map<String, String[]> params = request.getParameterMap(); // 当前请求链接后的参数对象（?name=lx&age=25&sex=1）
        StringBuilder queryParms = new StringBuilder();
        // 获取包含映射关系的set视图
        Set<Map.Entry<String, String[]>> paramsSet = params.entrySet();
        // 遍历参数生成查询参数
        for (Map.Entry<String, String[]> paramSet : paramsSet) {
            for (String param : paramSet.getValue()) {
                queryParms.append("&").append(paramSet.getKey()).append("=").append(param);
            }
        }
        if (StrUtil.isEffective(queryParms.toString())) {
            requestUrl.append("?").append(queryParms.toString().substring(1));
        }

        return requestUrl.toString();
    }

    /**
     * @Description TODO 获取真实的ip地址
     * @Author lixing
     * @Date 2020/4/4 21:34
     * @Param [request]
     * @return java.lang.String
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StrUtil.isEffective(ip) && !"unKnown".equalsIgnoreCase(ip)){
            int index = ip.indexOf(","); // //多次反向代理后会有多个ip值，第一个ip才是真实ip
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StrUtil.isEffective(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static String getBaseErrorUrl(HttpServletRequest request, String baseErrorUrl) {
        String scheme = request.getScheme(); // http
        String serverName = request.getServerName(); // localhost
        String serverPort = String.valueOf(request.getServerPort()); // 8080
        String contextPath = request.getContextPath(); // /warboot
        String currentReqUrl = getRequestUrl(request);
        if (currentReqUrl.contains(baseErrorUrl)) {
            baseErrorUrl = currentReqUrl;
        } else {
            if ("192.168.223.128".equals(serverName) || "localhost".equals(serverName) || "8080".equals(serverPort)) {
                baseErrorUrl = MessageFormat.format("{0}://{1}:{2}{3}{4}", scheme, serverName, serverPort, contextPath, baseErrorUrl);
            } else {
                baseErrorUrl = MessageFormat.format("{0}://{1}{2}{3}", scheme, serverName, contextPath, baseErrorUrl);
            }
        }
        return baseErrorUrl;
    }

    /**
     * @Description 获取HttpServletRequest对象中请求参数
     * @Author lixing
     * @Date 2020/10/29 15:43
     * @Param [request]
     * @return java.lang.String
     */
    public static String getRequestParamForWeChat(HttpServletRequest request) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder stringBuffer = new StringBuilder();
        String param = null;
        while ((param = bufferedReader.readLine()) != null) {
            stringBuffer.append(param);
        }
        return stringBuffer.toString();
    }

    /**
     * @Description 获取HttpServletRequest对象中请求参数
     * @Author lixing
     * @Date 2021/7/9 10:54
     * @Param [callbackParam]
     * @return java.util.LinkedHashMap<java.lang.String,java.lang.String>
     */
    public static Map<String,String> getRequestParamForAlibaba(HttpServletRequest request) {
        Map<String,String> mapCallbackParam = new HashMap<String,String>(50);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            mapCallbackParam.put(name, new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        }
        return mapCallbackParam;
    }

    /**
     * @Description 格式化回调参数
     * @Author lixing
     * @Date 2021/7/9 10:54
     * @Param [callbackParam]
     * @return java.util.LinkedHashMap<java.lang.String,java.lang.String>
     */
    public static LinkedHashMap<String,String> formatCallbackParam(String callbackParam) throws UnsupportedEncodingException {
        // 对待签名字符串数据通过&进行拆分
        String[] temp = callbackParam.split("&");
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
        //把拆分数据放在map集合内
        for (String s : temp) {
            //通过"="号分割成2个数据
            String[] arr = s.split("=", 2);
            //再开辟一个数组用来接收分割后的数据
            String[] tempAagin = new String[arr.length];
            System.arraycopy(arr, 0, tempAagin, 0, arr.length);
            linkedHashMap.put(tempAagin[0], URLDecoder.decode(tempAagin[1], "UTF-8"));
        }
        return linkedHashMap;
    }

}
